﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Xml.Linq;
using System.IO;
using System.Data.SqlClient;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using Top.Api.Domain;
using Top.Api.Util;
using Top.Api.Sync;
using Top.Api.Stream;
using CSM.Models;
using CSM.Controllers;
using CSM.Views;

namespace CSM
{
    public class Global : System.Web.HttpApplication
    {
        static CustomDataContext db = new CustomDataContext();
        static string appkey = (from a in db.TCrm_JC_Parameter where a.IsTB == true select a.AppID).Single().ToString();
        static string appsecret = (from a in db.TCrm_JC_Parameter where a.IsTB == true select a.AppSecret).Single().ToString(); //"4a3af04b25ea0e840b66e1bd82056099";
        static string url = "http://gw.api.taobao.com/router/rest";
        static string sessionKey = PublicMethod.TranstoTrue((from a in db.TCrm_JC_Parameter where a.IsTB == true select a.SessionKey).Single().ToString());//"61026101e024234f491313f4539508ae94fe847bbf14a4275764683";
        protected void Application_Start(object sender, EventArgs e)
        {
            System.Timers.Timer myTimer = new System.Timers.Timer(60000);
            System.Timers.Timer myTimer2 = new System.Timers.Timer(3600000);
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(UpdateIncrement);
            myTimer.Interval = 60000;
            myTimer.Enabled =false;
            myTimer2.Elapsed += new System.Timers.ElapsedEventHandler(UpdateDay);
            myTimer2.Interval = 3600000;
            myTimer2.Enabled =false;
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
        private static void UpdateIncrement(object source, System.Timers.ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour == 23)
            {
                
            }
            else
            {
                ITopClient client = new DefaultTopClient(url, appkey, appsecret);
                TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest();
                req.Fields = "seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type";
                DateTime dateTime1 = DateTime.Now;
                req.EndModified = dateTime1;
                DateTime dateTime = DateTime.Now.AddMinutes(-5);
                req.StartModified = dateTime;
                req.PageSize = 100L;
                TradesSoldIncrementGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    if (response.TotalResults != 0)
                    {
                        long pageCount = ((response.TotalResults + req.PageSize - 1) / req.PageSize).Value;
                        while (pageCount > 0)
                        {
                            req.PageNo = pageCount;
                            req.UseHasNext = true;
                            response = client.Execute(req, sessionKey);
                            if (!response.IsError)
                            {
                                foreach (Trade trade in response.Trades)
                                {
                                    
                                    Trade tradeinfo = GetTradeFullInfo(trade.Tid, sessionKey);
                                    var query = from a in db.TCrm_KF_Orders where a.tid == Convert.ToString(tradeinfo.Tid) select a;
                                    var querycustomer = from a in db.TCrm_KF_Customer where a.TbID == tradeinfo.BuyerNick select a;
                                    if (query.Count() == 0)
                                    {
                                        TCrm_KF_Orders myrow = new TCrm_KF_Orders();
                                        myrow.buyer_nick = tradeinfo.BuyerNick;
                                        myrow.alipay_id = tradeinfo.AlipayId.ToString();
                                        myrow.shipping_type = tradeinfo.ShippingType;
                                        myrow.receiver_mobile = tradeinfo.ReceiverPhone;
                                        myrow.tid = tradeinfo.Tid.ToString();
                                        myrow.status = tradeinfo.Status;
                                        myrow.created = Convert.ToDateTime(tradeinfo.Created);
                                        myrow.payment = Convert.ToDecimal(tradeinfo.Price);
                                        myrow.pay_time = Convert.ToDateTime(tradeinfo.PayTime);
                                        myrow.post_fee = Convert.ToDecimal(tradeinfo.PostFee);
                                        myrow.item_title = tradeinfo.Title;
                                        myrow.num = Convert.ToInt32(tradeinfo.Num);
                                        myrow.receiver_address = tradeinfo.ReceiverAddress;
                                        myrow.receiver_name = tradeinfo.ReceiverName;
                                        myrow.receiver_phone = tradeinfo.ReceiverPhone;
                                        myrow.total_fee = Convert.ToDecimal(tradeinfo.Payment);
                                        db.TCrm_KF_Orders.InsertOnSubmit(myrow);
                                        db.SubmitChanges();
                                    }
                                    if (querycustomer.Count() == 0)
                                    {
                                        TCrm_KF_Customer newrow = new TCrm_KF_Customer();
                                        newrow.Address = tradeinfo.ReceiverAddress;
                                        newrow.AliPayID = tradeinfo.AlipayId.ToString();
                                        newrow.AllMoney = Convert.ToDecimal(trade.TotalFee);
                                        newrow.Belongto = "";
                                        newrow.BlackList = false;
                                        newrow.CustomerID = PublicMethod.CreateCustomer();
                                        newrow.CustomerName = tradeinfo.ReceiverName;
                                        newrow.Email=trade.BuyerEmail;
                                        newrow.FinalTime = Convert.ToDateTime(trade.Created);
                                        newrow.Frequence = "1";
                                        newrow.Postal = trade.ReceiverZip;
                                        newrow.IsLock = false;
                                        newrow.NoCall = false;
                                        newrow.Province = PublicMethod.GetProvince(tradeinfo.ReceiverAddress);
                                        newrow.ReceiverName = tradeinfo.ReceiverName;
                                        newrow.ShopID = trade.SellerNick;
                                        newrow.TbID = trade.BuyerNick;
                                        db.SubmitChanges();
                                    }
                                    if (querycustomer.Count() != 0)
                                    {
                                        var queryfirst = querycustomer.First();
                                        queryfirst.AllMoney += Convert.ToDecimal(trade.TotalFee);
                                        queryfirst.Frequence += (Convert.ToInt32(queryfirst.Frequence) + 1).ToString();
                                        queryfirst.FinalTime = Convert.ToDateTime(trade.Created);
                                    }
                                }
                                pageCount--;
                            }
                        }
                    }
                }
            }
        }
        private static Trade GetTradeFullInfo(long tid, String sessionKey)
        {
            ITopClient client = new DefaultTopClient(url, appkey, appsecret);
            TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
            req.Fields = "seller_nick,buyer_nick,title,type,created,sid,tid,seller_rate,buyer_rate,status,payment,discount_fee,adjust_fee,post_fee,total_fee,pay_time,end_time,modified,consign_time,buyer_obtain_point_fee,point_fee,real_point_fee,received_payment,commission_fee,pic_path,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type";
            req.Tid = tid;
            TradeFullinfoGetResponse response = client.Execute(req, sessionKey);
            if (!response.IsError)
            {
                return response.Trade;
            }
            else
            {
                return null;
            }
        }
        private static void UpdateDay(object source, System.Timers.ElapsedEventArgs e)
        {
            //间隔时间执行某动作
            if (DateTime.Now.Hour !=23)
            {
                //System.Threading.Thread.Sleep(30000);
            }
            else
            {
                ITopClient client = new DefaultTopClient(url, appkey, appsecret);
                TradesSoldGetRequest req = new TradesSoldGetRequest();
                req.Fields = "tid";
                req.StartCreated =DateTime.Today.AddHours(-24);
                req.EndCreated = DateTime.Now;
                //req.StartCreated =Convert.ToDateTime("2000-01-01 00:00:00");
                TradesSoldGetResponse response = client.Execute(req, sessionKey);
                if (!response.IsError)
                {
                    foreach (Trade trade in response.Trades)
                    {

                        Trade tradeinfo = GetTradeFullInfo(trade.Tid, sessionKey);
                        var query = from a in db.TCrm_KF_Orders where a.tid == Convert.ToString(tradeinfo.Tid) select a;
                        var querycustomer = from a in db.TCrm_KF_Customer where a.TbID == tradeinfo.BuyerNick select a;
                        if (query.Count() == 0)
                        {
                            TCrm_KF_Orders myrow = new TCrm_KF_Orders();
                            myrow.buyer_nick = tradeinfo.BuyerNick;
                            myrow.alipay_id = tradeinfo.AlipayId.ToString();
                            myrow.shipping_type = tradeinfo.ShippingType;
                            myrow.receiver_mobile = tradeinfo.ReceiverPhone;
                            myrow.tid = tradeinfo.Tid.ToString();
                            myrow.status = tradeinfo.Status;
                            myrow.created = Convert.ToDateTime(tradeinfo.Created);
                            myrow.payment = Convert.ToDecimal(tradeinfo.Price);
                            myrow.pay_time = Convert.ToDateTime(tradeinfo.PayTime);
                            myrow.post_fee = Convert.ToDecimal(tradeinfo.PostFee);
                            myrow.item_title = tradeinfo.Title;
                            myrow.num = Convert.ToInt32(tradeinfo.Num);
                            myrow.receiver_address = tradeinfo.ReceiverAddress;
                            myrow.receiver_name = tradeinfo.ReceiverName;
                            myrow.receiver_phone = tradeinfo.ReceiverPhone;
                            myrow.total_fee = Convert.ToDecimal(tradeinfo.Payment);
                            db.TCrm_KF_Orders.InsertOnSubmit(myrow);
                            db.SubmitChanges();
                        }
                        if (querycustomer.Count() == 0)
                        {
                            TCrm_KF_Customer newrow = new TCrm_KF_Customer();
                            newrow.Address = tradeinfo.ReceiverAddress;
                            newrow.AliPayID = tradeinfo.AlipayId.ToString();
                            newrow.AllMoney = Convert.ToDecimal(trade.TotalFee);
                            newrow.Belongto = "";
                            newrow.BlackList = false;
                            newrow.CustomerID = PublicMethod.CreateCustomer();
                            newrow.CustomerName = tradeinfo.ReceiverName;
                            newrow.Email = trade.BuyerEmail;
                            newrow.FinalTime = Convert.ToDateTime(trade.Created);
                            newrow.Frequence = "1";
                            newrow.Postal = trade.ReceiverZip;
                            newrow.IsLock = false;
                            newrow.NoCall = false;
                            newrow.Province = PublicMethod.GetProvince(tradeinfo.ReceiverAddress);
                            newrow.ReceiverName = tradeinfo.ReceiverName;
                            newrow.ShopID = trade.SellerNick;
                            newrow.TbID = trade.BuyerNick;
                            db.SubmitChanges();
                        }
                        if (querycustomer.Count() != 0)
                        {
                            var queryfirst = querycustomer.First();
                            queryfirst.AllMoney += Convert.ToDecimal(trade.TotalFee);
                            queryfirst.Frequence += (Convert.ToInt32(queryfirst.Frequence) + 1).ToString();
                            queryfirst.FinalTime = Convert.ToDateTime(trade.Created);
                        }
                    }
                }
            }
        }
    }
}